﻿#include "TestBoxUpdaterDialog.h"
#include "ui_TestBoxUpdaterDialog.h"
#include "components/Toast/Toast.h"
#include "utils/String/IntelHexParser.h"
#include "stores/DataStroes.h"
#include "services/tlv/Com/TlvThreadCom.h"

#include <QFileDialog>
#include "components/FWidgets/FMessageBox/FMessageBox.h"
#include <QDebug>


TestBoxUpdaterDialog::TestBoxUpdaterDialog(QWidget *parent)
    : FDialog(parent)
    , ui(new Ui::TestBoxUpdaterDialog)
    , m_task(new TBUTask)
{
    ui->setupUi(this);
    setWindowFlag(Qt::WindowContextHelpButtonHint, false);
    setWindowTitle(tr("TestBoxUpdater"));

    ui->btnRun->setOnIcon(QIcon(":/imgs/stop.png"));
    ui->leHexFilePath->setText(DataStroes::instance()->tlvPrj()->model().data().hex_file);

    connect(m_task, &TBUTask::errorOccurred, this, [=](const QString& msg){
        Toast::error(msg);
    });
    connect(m_task, &TBUTask::hasDone, ui->progressBar, &QProgressBar::setValue);
    connect(m_task, &TBUTask::taskStarted, this, [=](){
        ui->btnRun->setIconStatus(true);
    });
    connect(m_task, &TBUTask::taskFinished, this, [=](){
        ui->btnRun->setIconStatus(false);
        Toast::success(tr("Flash Done!"));
    });
    connect(m_task, &TBUTask::taskStopped, this, [=](){
        ui->btnRun->setIconStatus(false);
    });
}

TestBoxUpdaterDialog::~TestBoxUpdaterDialog()
{
    m_task->stop();
    delete m_task;
    delete ui;
}

void TestBoxUpdaterDialog::showToast()
{
    Toast::warning(tr("Please wait for the upgrade to end."));
}

bool TestBoxUpdaterDialog::initHexFile(const QString &hexPath)
{
    QFile f(hexPath);
    if (!f.open(QIODevice::ReadOnly)) {
        Toast::error(tr("Open file failed!\n%1").arg(hexPath));
        return false;
    }
    QString hexStr = f.readAll();

    IntelHexParser parser(hexStr);
    if (!parser.parse()) {
        Toast::error(parser.errorString());
        return false;
    }
    uint32_t base = 0x00;
    auto res1 = parser.toContiguousImage(base);
    m_task->setMemData(res1);
    return true;
}

void TestBoxUpdaterDialog::closeEvent(QCloseEvent *e)
{
    if (m_task->isRunning()) {
        e->ignore();
        showToast();
    } else {
        QDialog::closeEvent(e);
    }
}

void TestBoxUpdaterDialog::reject()
{
    if (m_task->isRunning()) {
        showToast();
    } else {
        QDialog::reject();
    }
}

void TestBoxUpdaterDialog::on_btnCancel_clicked()
{
    if (m_task->isRunning()) {
        showToast();
    } else {
        accept();
    }
}


void TestBoxUpdaterDialog::on_btnBrowse_clicked()
{
    if (m_task->isRunning()) {
        showToast();
        return;
    }
    QString hexPath = QFileDialog::getOpenFileName(this, tr("Open .hex file"), "", tr("Intel Hex File (*.hex)"));
    if (hexPath.isEmpty()) return;
    ui->leHexFilePath->setText(hexPath);
    ui->progressBar->setValue(0);
    DataStroes::instance()->tlvPrj()->model().data().hex_file = hexPath;
}


void TestBoxUpdaterDialog::on_btnRun_clicked()
{
    QString hexPath = ui->leHexFilePath->text();
    if (hexPath.isEmpty()) {
        Toast::warning(tr("Select hex file please!"));
        return;
    }
    if (!TlvThreadCom::instance()->isOpen()) {
        Toast::error(ICom::ERR_NOT_OPEN());
        return;
    }
    if (m_task->isRunning()) {
        showToast();
        return;
    }

    if (!initHexFile(hexPath)) {
        return;
    }

    auto res = FMessageBox::information(this, tr("Tip"), tr("Please disconnect from the screen before upgrading!"));
    if (FMessageBox::Ok == res) {
        m_task->start();
    }
}

